<?php

Yii::import('ext.runactions.components.ERunActions');

class SubscribtionController extends Controller
{
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionSubscribe()
	{
		$model = new Subscribers;
		$model->email = $_POST['email'];
		$catalog;
		if(isset($_POST['catalog_id'])){
			//$model->catalog_id = intval($_POST['catalog_id']);
			$catalog = Catalog::model()->findByPk(intval($_POST['catalog_id']));
			$model->catalogs = array($catalog);
		}
		$model->withRelated->save(true, array('catalogs'));
		if(isset($catalog)){
			Yii::app()->user->setFlash('subscribe-lead','You have successfuly subscribed to catalog "'.$catalog->title.'".');
			Yii::app()->user->setFlash('subscribe','Thank you for subscribing us. We will send you all news in catalog "'.$catalog->title.'" to keep you informed.');
		}else{
			Yii::app()->user->setFlash('subscribe-lead','You have successfuly subscribed.');
			Yii::app()->user->setFlash('subscribe','Thank you for subscribing us. We will send you all news to keep you informed.');
		}
		$this->redirect(CHttpRequest::getUrlReferrer());
	}

	public function actionUnsubscribe($email, $catalog_id)
	{
		
	}

	public function actionRun()
	{
		$catalog_id=$_POST['catalog_id'];
		if (ERunActions::runBackground())
        {
        	mail(Yii::app()->params['adminEmail'],$catalog_id,"model body","headers");
        }else{
        	$this->redirect(Yii::app()->createAbsoluteUrl('site/index'));
    	}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Catalog the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Subscribers::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
